import asyncio
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
    AsyncEngine,
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)
from sqlalchemy.pool import StaticPool

from .file_storage import ROOT_DIR
from model import Base  # 确保模型已定义

# ---------- 配置 ----------
DB_PATH = ROOT_DIR / "bidding.db"
DATABASE_URL = f"sqlite+aiosqlite:///{DB_PATH}"

# 全局变量
_engine: AsyncEngine | None = None
_async_sessionmaker: async_sessionmaker | None = None
_init_lock = asyncio.Lock()  # 确保初始化只做一次
_initialized = False


# ---------- 核心函数 ----------
async def _create_engine_and_tables() -> AsyncEngine:
    """创建引擎并确保表存在"""
    global _initialized
    engine = create_async_engine(
        DATABASE_URL,
        echo=False,
        poolclass=StaticPool,  # 推荐用于单文件 SQLite
        connect_args={"check_same_thread": False},
    )

    # 自动建表（如果不存在）
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    _initialized = True
    return engine


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """
    获取数据库会话（可用于 FastAPI Depends）
    惰性初始化：第一次调用时才创建引擎和表
    """
    global _engine, _async_sessionmaker

    # 使用锁防止并发初始化
    async with _init_lock:
        if _engine is None:
            _engine = await _create_engine_and_tables()
            _async_sessionmaker = async_sessionmaker(
                bind=_engine,
                class_=AsyncSession,
                expire_on_commit=False,
            )

    # 创建会话
    async with _async_sessionmaker() as session:
        yield session